Page({
  data: {
    newsList: [],
    loading: false,
    finished: false,
    refreshing: false,
    selectedCategory: 0,
    selectedSort: 0,
    categories: [],
    pageSize: 10,
    currentPage: 1,
    totalPages: 0,
    categoryOptions: [{text: '全部分类', value: 0}],
    sortOptions: [
      {text: '最新发布', value: 0},
      {text: '最多阅读', value: 1}
    ]
  },

  onLoad() {
    this.fetchCategories()
    this.loadNews(true)
  },

  fetchCategories() {
    const { articleApi } = require('../../utils/api')
    articleApi.getAllCategories()
      .then(res => {
        // 统一处理API响应格式
        const data = res.data?.list || res.data || []
        const categoryOptions = [
          {text: '全部分类', value: 0},
          ...data.map((item, index) => ({
            text: item.name || item.categoryName,
            value: index + 1
          }))
        ]
        this.setData({
          categories: data.map(item => item.name || item.categoryName),
          categoryOptions
        })
      })
      .catch(err => {
        console.error('获取分类失败:', err)
        wx.showToast({
          title: '获取分类失败',
          icon: 'none'
        })
      })
  },

  loadNews(isRefresh = false) {
    if (isRefresh) {
      this.setData({
        currentPage: 1,
        newsList: [],
        finished: false
      })
    }

    const { articleApi } = require('../../utils/api')
    const params = {
      page: this.data.currentPage,
      size: this.data.pageSize
    }
    
    if (this.data.selectedCategory > 0) {
      params.category = this.data.categories[this.data.selectedCategory - 1]
    }

    articleApi.getArticleList(params)
      .then(res => {
        console.log('API响应数据:', res) // 调试日志
        if (!res.data) {
          throw new Error('API返回数据格式不正确')
        }
        // 兼容多种后端返回格式
        const list = res.data?.list || res.data?.data || res.data || []
        console.log('新闻列表原始数据:', list)
        const validList = list.filter(item => {
          const id = String(item.newsId || item.id)
          const isValid = /^\d{5,}$/.test(id)
          if (!isValid) {
            console.error('过滤无效文章ID:', id, '标题:', item.title)
          }
          return isValid
        })
        
        console.log('有效新闻列表ID检查:', validList.map(item => ({
          id: String(item.newsId || item.id),
          title: item.title
        })))
        
        if (list.length === 0) {
          console.warn('API返回空列表')
        }
        
        const total = res.data?.total || list.length
        const pages = res.data?.pages || Math.ceil(total / this.data.pageSize)
        
        this.setData({
          newsList: this.data.newsList.concat(validList.map(item => ({
            id: String(item.newsId || item.id),
            title: item.title,
            contentPreview: item.contentText || '',
            category: item.category,
            pubTime: item.pubTime,
            imageUrl: item.imageUrl || '/static/logo.png'
          }))),
          currentPage: this.data.currentPage + 1,
          finished: list.length < this.data.pageSize,
          totalPages: pages
        })
      })
      .catch(err => {
        console.error('获取新闻列表失败:', err)
        wx.showToast({
          title: '获取新闻失败',
          icon: 'none'
        })
      })
  },

  onRefresh() {
    this.setData({refreshing: true})
    this.loadNews(true)
    this.setData({refreshing: false})
  },

  handleCategoryChange(e) {
    this.setData({selectedCategory: e.detail.value})
    this.onRefresh()
  },

  handleSortChange(e) {
    this.setData({selectedSort: e.detail.value})
    this.onRefresh()
  },

  goToDetail(e) {
    const item = e.currentTarget.dataset.item
    const newsId = String(item.newsId || item.id).trim()
    console.log('跳转详情页ID:', newsId)
    
    if (!/^\d{5,}$/.test(newsId)) {
      wx.showToast({
        title: '文章ID必须为5位以上数字',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/news/detail?id=${newsId}`,
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '跳转详情页失败',
          icon: 'none'
        })
      }
    })
  },

  scrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  formatTime(dateString) {
    if (!dateString) return ''
    const date = new Date(dateString)
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  }
})
